package com.soar.framework.bll;

import com.soar.framework.app.FrameworkConstants;
import com.soar.framework.net.http.OkHttpUtils;
import com.soar.framework.net.http.builder.GetBuilder;
import com.soar.framework.net.http.builder.OkHttpRequestBuilder;
import com.soar.framework.net.http.builder.PostFileBuilder;
import com.soar.framework.net.http.builder.PostFormBuilder;
import com.soar.framework.net.http.builder.PostStringBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class SoarHttpRequest {

    private static void addAppHeader(OkHttpRequestBuilder okHttpRequestBuilder) {
        okHttpRequestBuilder
                .addHeader("X-App-Id", FrameworkConstants.PARAMS_APP_ID)
                .addHeader("X-UDID", FrameworkConstants.PARAMS_UDID)
                .addHeader("X-Access-Token", FrameworkConstants.PARAMS_TOKEN)
                .addHeader("Accept-Language", "zh-CN");
    }

    /**
     * okhttp不支持中文
     * 一定要转码
     *
     * @param value 可能中文
     * @return utf-8 转码后格式
     */
    private static String getValueEncoded(String value) {
        if (value == null) return "unknown";
        String newValue = value.replace("\n", "");
        for (int i = 0, length = newValue.length(); i < length; i++) {
            char c = newValue.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                try {
                    return URLEncoder.encode(newValue, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return "unknown";
                }
            }
        }
        return newValue;
    }

    public static PostFormBuilder post() {
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        addAppHeader(postFormBuilder);
        return postFormBuilder;
    }

    public static GetBuilder get() {
        GetBuilder getBuilder = OkHttpUtils.get();
        addAppHeader(getBuilder);
        return getBuilder;
    }

    public static PostFileBuilder uploadFile() {
        PostFileBuilder postFileBuilder = OkHttpUtils.postFile();
        addAppHeader(postFileBuilder);
        return postFileBuilder;
    }

    public static PostStringBuilder uploadJson() {
        PostStringBuilder stringBuilder = OkHttpUtils.postString();
        addAppHeader(stringBuilder);
        return stringBuilder;
    }

}
